package com.jsmtr.rms.controller;

import cn.ktjk.DataTableUtile.DataTable.DataRow;
import cn.ktjk.DataTableUtile.DataTable.DataTable;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.entity.vo.DoMSResultForm;
import com.jsmtr.rms.service.*;
import com.jsmtr.rms.utils.*;
import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/Do/SS")//素质测试
public class DoSSController {

    @Resource
    private IBaseEvaluationService baseEvaluationService;
    @Resource
    private IBaseExaminerService baseExaminerService;
    @Resource
    private IUtilService utilService;
    @Resource
    private IDoMSService msService;
    @Resource
    private IProjectService projectService;
    @Resource
    private INZService nzService;
    @Resource
    private IDoSZService szService;
    @Resource
    private IRecommendService recommendService;

    @Resource
    private IDoResumeService doResumeService;


    //region [start] 面试安排
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/PlanAction", method = RequestMethod.POST)
    public void PlanAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择参加面试的人员！", "no", response);
            } else {
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String pid = request.getParameter("pid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                String examinerid = request.getParameter("examinerid").trim();//面试组ID
                String examinername = baseExaminerService.getGroup(examinerid).getName();//面试组名称
                String evaluationid = request.getParameter("evaluationid").trim();//评价表ID
                String evaluationname = baseEvaluationService.getTable(evaluationid).getName();//评价表名称
                String starttime = request.getParameter("starttime").trim();//面试时间
                String address = request.getParameter("address").trim();//面试地点
                String endtime = request.getParameter("endtime");//确认截止时间
                String mszysx = request.getParameter("mszysx");
                BaseUser cuser = utilService.getSessionUser(request);
                if (cuser.getUdept().equals(deptcode)) {
                    if (utilService.FlowIsDoing(fid)) {
                        List list = new ArrayList();
                        String gid = UUID.randomUUID().toString();
                        //面试组
                        List<BaseExaminer> examiners = baseExaminerService.getBaseExaminers(examinerid);
                        for (BaseExaminer examiner : examiners) {
                            DoMSExaminer dest = new DoMSExaminer();
                            BeanTools.Copy(examiner, dest);
                            dest.setId(UUID.randomUUID().toString());
                            dest.setGid(gid);
                            dest.setFid(fid);
                            list.add(dest);
                        }
                        //评价表
                        List<BaseEvaluationItem> items = baseEvaluationService.getBaseEvaluationItems(evaluationid);
                        for (BaseEvaluationItem item : items) {
                            DoMSEvaluation dest = new DoMSEvaluation();
                            BeanTools.Copy(item, dest);
                            dest.setId(UUID.randomUUID().toString());
                            dest.setGid(gid);
                            list.add(dest);
                        }

                        int count = 1 + msService.getMsCount(fid);

                        List editList = new ArrayList();
                        //面试计划
                        for (String uid : uids) {
                            DoMSUser cmsuser = msService.getMsUser(fid, uid);
                            if (cmsuser == null) {
                                DoMSUser msuser = new DoMSUser();
                                msuser.setId(UUID.randomUUID().toString());
                                msuser.setAddress(address);
                                msuser.setEvaluationname(evaluationname);
                                msuser.setExaminercount(examiners.size());
                                msuser.setExaminername(examinername);
                                msuser.setFid(fid);
                                msuser.setGid(gid);
                                msuser.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                                msuser.setResult("未面试");
                                msuser.setStarttime(starttime);
                                msuser.setUserid(uid);
                                msuser.setPointuser(",");
                                msuser.setNum(String.valueOf(count));
                                list.add(msuser);
                                if (endtime != null && endtime.trim().length() > 0) {
                                    DoMSConfirm msConfirm = new DoMSConfirm();
                                    msConfirm.setId(UUID.randomUUID().toString());
                                    msConfirm.setMsuserid(msuser.getId());
                                    msConfirm.setEndtime(endtime.trim());
                                    msConfirm.setIsconfirm("否");
                                    msConfirm.setType("MS");
                                    list.add(msConfirm);
                                }
                                if (mszysx != null && mszysx.trim().length() > 0) {
                                    DoZysx zysx = new DoZysx();
                                    zysx.setId(UUID.randomUUID().toString());
                                    zysx.setFid(fid);
                                    zysx.setPid(pid);
                                    zysx.setRemark(mszysx);
                                    zysx.setUserid(uid);
                                    zysx.setType("MS");
                                    zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                    zysx.setAdduser(cuser.getUcode());
                                    list.add(zysx);
                                }
                                count++;

                            } else {
                                cmsuser.setAddress(address);
                                cmsuser.setEvaluationname(evaluationname);
                                cmsuser.setExaminercount(examiners.size());
                                cmsuser.setExaminername(examinername);
                                cmsuser.setFid(fid);
                                cmsuser.setGid(gid);
                                if (!cmsuser.getNotice().equals(EnumTools.NoticeState.已发通知.ordinal())) {
                                    cmsuser.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                                }
                                if (cmsuser.getResult().equalsIgnoreCase("未面试")) {
                                    cmsuser.setUserid(uid);
                                    cmsuser.setPointuser("");
                                    cmsuser.setNum(String.valueOf(count));
                                }
                                cmsuser.setStarttime(starttime);
                                editList.add(cmsuser);
                                if (endtime != null && endtime.trim().length() > 0) {
                                    DoMSConfirm msConfirm = utilService.getMSUserConfirm(cmsuser.getId());
                                    if (msConfirm == null) {
                                        msConfirm = new DoMSConfirm();
                                        msConfirm.setId(UUID.randomUUID().toString());
                                        msConfirm.setMsuserid(cmsuser.getId());
                                        msConfirm.setEndtime(endtime.trim());
                                        msConfirm.setIsconfirm("否");
                                        msConfirm.setType("MS");
                                        list.add(msConfirm);
                                    } else {
                                        if (msConfirm.getIsconfirm().equalsIgnoreCase("否")) {
                                            msConfirm.setEndtime(endtime.trim());
                                            editList.add(msConfirm);
                                        }
                                    }

                                } else {
                                    DoMSConfirm msConfirm = utilService.getMSUserConfirm(cmsuser.getId());
                                    if (msConfirm != null) {
                                        utilService.delObject(msConfirm);
                                    }
                                }
                                if (mszysx != null && mszysx.trim().length() > 0) {
                                    DoZysx zysx = utilService.getUserZysx(pid, fid, uid);
                                    if (zysx == null) {
                                        zysx = new DoZysx();
                                        zysx.setId(UUID.randomUUID().toString());
                                        zysx.setFid(fid);
                                        zysx.setPid(pid);
                                        zysx.setRemark(mszysx);
                                        zysx.setUserid(uid);
                                        zysx.setType("MS");
                                        zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        zysx.setAdduser(cuser.getUcode());
                                        list.add(zysx);
                                    } else {
                                        zysx.setRemark(mszysx);
                                        zysx.setType("MS");
                                        zysx.setAddtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                        zysx.setAdduser(cuser.getUcode());
                                        editList.add(zysx);
                                    }
                                } else {
                                    DoZysx zysx = utilService.getUserZysx(pid, fid, uid);
                                    if (zysx != null) {
                                        utilService.delObject(zysx);
                                    }
                                }
                            }
                        }

                        utilService.editList(editList, list);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //endregion [end]

    //region [start] 查看面试评价表

    @RequestMapping("/viewEvaluation")
    public String viewEvaluation(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            DoMSUser user = msService.getMsUser(id);
            model.addAttribute("name", user.getEvaluationname());

            List<DoMSEvaluation> items = msService.getMSEvaluations(user.getGid());
            model.addAttribute("items", items);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Ms/evaluation";
    }

    //endregion [end]

    //region [start] 查看面试官

    @RequestMapping("/viewExaminer")
    public String viewExaminer(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            DoMSUser user = msService.getMsUser(id);
            model.addAttribute("name", user.getExaminername());

            List<DoMSExaminer> examiners = msService.getMSExaminers(user.getGid());
            model.addAttribute("examiners", examiners);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Ms/examiner";
    }

    //endregion [end]

    //startregion 编辑注意事项页面
    @RequestMapping("/editMszysx")
    public String editMszysx(HttpServletRequest request, Model model) {
        try {
            String mszysx = utilService.getConfig("mszysx");
            model.addAttribute("mszysx", mszysx);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Ms/editMszysx";
    }

    //endregion

    //region [start] 发短信
    @RequestMapping(value = "/MsgAction", method = RequestMethod.POST)
    public void MsgAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    String dxnr = request.getParameter("dxnr").trim();

                    List<Map<String, String>> msgs = new ArrayList<Map<String, String>>();

                    String[] uids = request.getParameterValues("uid");
                    if (uids == null) {
                        utilService.printJsonResult(false, "请选择参加面试的人员！", "no", response);
                        return;
                    }
                    ProjectInfo project = projectService.getpProjectById(pid);
                    List<Object[]> users = msService.getSsUser(uids, fid, project);

                    List<String> sqls = new ArrayList<String>();
                    for (Object[] user : users) {
                        //u.id,r.name,r.tel,u.notice
                        if (((BigDecimal) user[3]).intValue() == EnumTools.NoticeState.未发通知.ordinal()) {
                            //if (user[6].toString().equalsIgnoreCase("否")) {
                            sqls.add("update DoSS_User set notice='" + EnumTools.NoticeState.已发通知.ordinal() + "' where id='" + user[0] + "'");

                            //-------------短信----------------
                            Map<String, String> _map = new HashMap<String, String>();
                            _map.put("tel", user[2].toString());
                            _map.put("cont", dxnr.replace("{姓名}", user[1].toString()));
                            msgs.add(_map);
                        }
                    }
                    if (sqls.size() > 0) {
                        utilService.editSqls(sqls);
                        BaseMessageConfig messageConfig = utilService.getMessageConfig();
                        // 发送短信
                        if (PhoneTools.sendMsg(msgs, messageConfig.getUsername(), messageConfig.getPassword(), messageConfig.getHost())) {
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "短信发送失败！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "无可执行此操作的信息！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }

            utilService.printJsonResult(true, "操作成功", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }
    //endregion [end]

    //region [start] 面试成绩管理
    @RequestMapping("/index")
    public String index(Model model) {
        return "/Do/Ms/scoreindex";
    }
    //endregion [end]

    //region [start] 社会招聘评分

    //region 社会招聘
    @RequestMapping("/sz")
    public String sz(Model model) {
        model.addAttribute("type", EnumTools.RecruitType.社会招聘.ordinal());
        return "/Do/Ms/scoresz";
    }
    //endregion

    //region 获得社会招聘某待评分人员
    @SuppressWarnings("unchecked")
    @RequestMapping("/pointuser3")
    public void getMSPointUser3(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String fid = request.getParameter("fid").trim();//招聘流程ID
            BaseUser cuser = utilService.getSessionUser(request);

            Map<String, Object> map = msService.getSZPointUsers(page, perpage, fid);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                for (Object[] _user : (List<Object[]>) object) {
                    //r.id,u.id as msuid,r.code,r.name,r.educationname,r.workexperience,
                    //r.tel,u.starttime,u.address,r.fqstate,u.pointuser,r.fid,u.num
					/*result.append("<tr><td>" + _user[2] + "</td>");
					result.append("<td class='link'><a target='_blank' href='"
							+ request.getContextPath() + "/Do/SZResume/View?id="
							+ _user[0] + "'>" + _user[3]
							+ "</a></td>");*/
                    result.append("<tr><td>" + _user[12] + "</td>");
                    result.append("<td>" + _user[4] + "</td>");
                    result.append("<td>" + _user[5] + "年</td>");
                    result.append("<td>" + _user[6] + "</td>");
                    result.append("<td>" + _user[7] + "</td>");
                    result.append("<td>" + _user[8] + "</td>");
                    if (_user[9].equals("已放弃")) {
                        result.append("<td class='true'><span>已放弃</span></td></tr>");
                    } else {
                        if (_user[10].toString().contains(cuser.getUcode())) {
                            if (_user[11].equals(fid)) {
                                result.append("<td class='link'><a href=\"javascript:score('" + _user[1] + "')\">修改结果</a></td></tr>");
                            } else {
                                result.append("<td class='false'><span>已完成</span></td></tr>");
                            }

                        } else {
                            result.append("<td class='link'><a href=\"javascript:score('" + _user[1] + "')\">录入结果</a></td></tr>");
                        }
                    }
                }
            } else {
                result.append("<tr><td colspan='8'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/pointuser3Json")
    public LayuiDataTableResultBean pointuser3Json(
            HttpServletRequest request,
            @RequestParam(required = true) int page,
            @RequestParam(required = true) int limit,
            @RequestParam String fid
    ) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            fid = fid.trim();
            BaseUser cuser = utilService.getSessionUser(request);

            Map<String, Object> map = msService.getSZPointUsers(page, limit, fid);
            JSONArray data = new JSONArray();
            List<Object[]> list = (List<Object[]>) map.get("list");
            for (Object[] object :
                    list) {
                JSONObject item = new JSONObject();
                item.put("id", object[1]);
                item.put("name", object[3]);
                item.put("educationname", object[4]);
                item.put("workexperience",object[5]);
                item.put("tel",object[6]);
                item.put("starttime",object[7]);
                item.put("address",object[8]);
                item.put("fqstate",object[9]);
                item.put("pointuser",object[10]);
                item.put("fid",object[11]);
                item.put("num",object[12]);
                String rslt;
                if ("已放弃".equals(object[9])) {
                    rslt = "已放弃";
                } else if (object[10].toString().contains(cuser.getUcode())) {
                    if (object[11].equals(fid)) {
                        rslt = "修改结果";
                    } else {
                        rslt = "已完成";
                    }
                } else {
                    rslt = "录入结果";
                }


                item.put("result", rslt);

                data.add(item);
            }

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    //endregion

    //endregion [end]

    //region[start] 高校校园招聘评分

    //region 高校校园招聘
    @RequestMapping("/gx")
    public String gx(Model model) {
        model.addAttribute("type", EnumTools.RecruitType.高校校园招聘.ordinal());
        return "/Do/Ms/scoregx";
    }
    //endregion

    //region 获得高校校园招聘某待评分人员
    @SuppressWarnings("unchecked")
    @RequestMapping("/pointuser1")
    public void getMSPointUser1(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String fid = request.getParameter("fid").trim();//招聘流程ID
            BaseUser cuser = utilService.getSessionUser(request);

            Map<String, Object> map = msService.getGXPointUsers(page, perpage, fid);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                for (Object[] _user : (List<Object[]>) object) {
                    //u.num,r.university,r.majorname,r.educationname,u.starttime,u.address,
                    //u.id,r.fqstate,u.pointuser,r.fid
                    result.append("<tr><td>" + _user[0] + "</td>");
                    result.append("<td>" + _user[1] + "</td>");
                    result.append("<td>" + _user[2] + "</td>");
                    result.append("<td>" + _user[3] + "</td>");
                    result.append("<td>" + _user[4] + "</td>");
                    result.append("<td>" + _user[5] + "</td>");
                    if (_user[7].equals("已放弃")) {
                        result.append("<td class='true'><span>已放弃</span></td></tr>");
                    } else {
                        if (_user[8].toString().contains(cuser.getUcode())) {
                            if (_user[9].equals(fid))
                                result.append("<td class='link'><a href=\"javascript:score('" + _user[6] + "')\">修改结果</a></td></tr>");
                            else result.append("<td class='false'><span>已完成</span></td></tr>");

                        } else {
                            result.append("<td class='link'><a href=\"javascript:score('" + _user[6] + "')\">录入结果</a></td></tr>");
                        }
                    }
                }
            } else {
                result.append("<tr><td colspan='7'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='7'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }


    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/pointuser1Json")
    public LayuiDataTableResultBean pointuser1Json(
            HttpServletRequest request,
            @RequestParam(required = true) int page,
            @RequestParam(required = true) int limit,
            @RequestParam String fid
    ) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            fid = fid.trim();
            BaseUser cuser = utilService.getSessionUser(request);

            Map<String, Object> map = msService.getGXPointUsers(page, limit, fid);
            JSONArray data = new JSONArray();
            List<Object[]> list = (List<Object[]>) map.get("list");
            for (Object[] object :
                    list) {
                JSONObject item = new JSONObject();
                item.put("num", object[0]);
                item.put("university", object[1]);
                item.put("majorname", object[2]);
                item.put("educationname", object[3]);
                item.put("starttime", object[4]);
                item.put("address",object[5]);
                item.put("id",object[6]);
//                item.put("starttime",object[7]);
//                item.put("address",object[8]);
//                item.put("fqstate",object[9]);
//                item.put("pointuser",object[10]);
//                item.put("fid",object[11]);
//                item.put("num",object[12]);
                String rslt;
                if ("已放弃".equals(object[7])) {
                    rslt = "已放弃";
                } else if (object[8].toString().contains(cuser.getUcode())) {
                    if (object[9].equals(fid)) {
                        rslt = "修改结果";
                    } else {
                        rslt = "已完成";
                    }
                } else {
                    rslt = "录入结果";
                }


                item.put("result", rslt);

                data.add(item);
            }

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    //endregion

    //endregion [end]

    //region [start] 内部招聘评分


    //region 内部招聘
    /*@RequestMapping("/nz")
    public String nz(Model model) {
        model.addAttribute("type", EnumTools.RecruitType.内部招聘.ordinal());
        return "/Do/Ms/scorenz";
    }*/
    //endregion

    //region 获得内部招聘某面试计划的人员
    @SuppressWarnings("unchecked")
    @RequestMapping("/pointuser4")
    public void getMSPointUser4(HttpServletRequest request, HttpServletResponse response, DNZResume user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String fid = request.getParameter("fid").trim();//招聘流程ID
            BaseUser cuser = utilService.getSessionUser(request);
            Map<String, Object> map = msService.getNZPointUsers(page, perpage, fid);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                for (Object[] _user : (List<Object[]>) object) {
                    //r.id,u.id as msuid,r.code,r.name,r.sex,r.age,r.zzmm,
                    //r.groupdate,r.education,r.tel,u.starttime,u.address,r.fqstate,u.pointuser,u.num
					/*result.append("<tr><td>" + _user[2] + "</td>");
					result.append("<td class='link'><a target='_blank' href='"
							+ request.getContextPath() + "/Do/NZApply/View?id="
							+ _user[0] + "'>" + _user[3]
							+ "</a></td>");
					result.append("<td>" + _user[4] + "</td>");
					result.append("<td>" + _user[5] + "</td>");*/
                    result.append("<tr><td>" + _user[12] + "</td>");
                    result.append("<td>" + _user[6] + "</td>");
                    result.append("<td>" + _user[7] + "</td>");
                    result.append("<td>" + _user[8] + "</td>");
                    result.append("<td>" + _user[9] + "</td>");
                    result.append("<td>" + _user[10] + "</td>");
                    result.append("<td>" + _user[11] + "</td>");
                    if (_user[12].equals("已放弃")) {
                        result.append("<td class='true'><span>已放弃</span></td></tr>");
                    } else {
                        if (_user[13].toString().contains(cuser.getUcode())) {
                            result.append("<td class='false'><span>已完成</span></td></tr>");
                            //result.append("<td class='link'><a href=\"javascript:score('"+_user[1]+"')\">修改结果</a></td></tr>");
                        } else {
                            result.append("<td class='link'><a href=\"javascript:score('" + _user[1] + "')\">录入结果</a></td></tr>");
                        }
                    }
                }
            } else {
                result.append("<tr><td colspan='8'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/pointuser4Json")
    public LayuiDataTableResultBean pointuser4Json(
            HttpServletRequest request,
            @RequestParam(required = true) int page,
            @RequestParam(required = true) int limit,
            @RequestParam String fid
    ) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            fid = fid.trim();
            BaseUser cuser = utilService.getSessionUser(request);

            Map<String, Object> map = msService.getNZPointUsers(page, limit, fid);
            JSONArray data = new JSONArray();
            List<Object[]> list = (List<Object[]>) map.get("list");
            for (Object[] object :
                    list) {
                JSONObject item = new JSONObject();
                item.put("id", object[1]);
                item.put("name", object[3]);
                item.put("educationname", object[4]);
                item.put("workexperience",object[5]);
                item.put("tel",object[6]);
                item.put("starttime",object[7]);
                item.put("address",object[8]);
                item.put("fqstate",object[9]);
                item.put("pointuser",object[10]);
                item.put("fid",object[11]);
                item.put("num",object[12]);
                String rslt;
                if ("已放弃".equals(object[9])) {
                    rslt = "已放弃";
                } else if (object[10].toString().contains(cuser.getUcode())) {
                    if (object[11].equals(fid)) {
                        rslt = "修改结果";
                    } else {
                        rslt = "已完成";
                    }
                } else {
                    rslt = "录入结果";
                }


                item.put("result", rslt);

                data.add(item);
            }

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    //endregion

    //endregion [end]

    //region [start] 中专校园招聘评分

    //region 中专校园招聘
    @RequestMapping("/zz")
    public String zz(Model model) {
        model.addAttribute("type", EnumTools.RecruitType.中专校园招聘.ordinal());
        return "/Do/Ms/scorezz";
    }
    //endregion

    //region 获得中专校招某面试计划的人员
    @SuppressWarnings("unchecked")
    @RequestMapping("/pointuser2")
    public void getMSPointUser2(HttpServletRequest request, HttpServletResponse response, DNZResume user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String fid = request.getParameter("fid").trim();//招聘流程ID
            BaseUser cuser = utilService.getSessionUser(request);
            Map<String, Object> map = msService.getZZPointUsers(page, perpage, fid);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                for (Object[] _user : (List<Object[]>) object) {
                    //r.id,u.id as msuid,r.name,r.gender,r.code,r.major,r.deptname,
                    //u.starttime,u.address,r.fqstate,u.pointuser,u.num
					/*result.append("<tr><td class='link'>");
					result.append("<a href=\"javascript:openLayer('查看毕业生信息','/Do/ZZRecommend/view?id="
							+ _user[0]
							+ "','800px','600px');\">"
							+ _user[2] + "</a></td>");
					result.append("<td>" + _user[3] + "</td>");
					result.append("<td>" + _user[4] + "</td>");*/
                    result.append("<tr><td>" + _user[11] + "</td>");
                    result.append("<td>" + _user[5] + "</td>");
                    result.append("<td>" + _user[6] + "</td>");
                    result.append("<td>" + (_user[7] == null ? "" : _user[7]) + "</td>");
                    result.append("<td>" + (_user[8] == null ? "" : _user[8]) + "</td>");
                    if (_user[9].equals("已放弃")) {
                        result.append("<td class='true'><span>已放弃</span></td></tr>");
                    } else {
                        if (_user[10].toString().contains(cuser.getUcode())) {
                            result.append("<td class='false'><span>已完成</span></td></tr>");
                            //result.append("<td class='link'><a href=\"javascript:score('"+_user[1]+"')\">修改结果</a></td></tr>");
                        } else {
                            result.append("<td class='link'><a href=\"javascript:score('" + _user[1] + "')\">录入结果</a></td></tr>");
                        }
                    }
                }
            } else {
                result.append("<tr><td colspan='8'>无符合条件的信息</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='8'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/pointuser2Json")
    public LayuiDataTableResultBean pointuser2Json(
            HttpServletRequest request,
            @RequestParam(required = true) int page,
            @RequestParam(required = true) int limit,
            @RequestParam String fid
    ) {
        LayuiDataTableResultBean result = new LayuiDataTableResultBean();
        try {
            fid = fid.trim();
            BaseUser cuser = utilService.getSessionUser(request);

            Map<String, Object> map = msService.getZZPointUsers(page, limit, fid);
            JSONArray data = new JSONArray();
            List<Object[]> list = (List<Object[]>) map.get("list");
            for (Object[] object :
                    list) {
                JSONObject item = new JSONObject();
                item.put("id", object[1]);
                item.put("gender", object[3]);
                item.put("code", object[4]);
                item.put("major",object[5]);
                item.put("deptname",object[6]);
                item.put("starttime",object[7]);
                item.put("address",object[8]);
                item.put("fqstate",object[9]);
                item.put("pointuser",object[10]);
                item.put("num",object[11]);
                String rslt;
                if ("已放弃".equals(object[9])) {
                    rslt = "已放弃";
                } else if (object[10].toString().contains(cuser.getUcode())) {
                    if (object[11].equals(fid)) {
                        rslt = "修改结果";
                    } else {
                        rslt = "已完成";
                    }
                } else {
                    rslt = "录入结果";
                }


                item.put("result", rslt);

                data.add(item);
            }

            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    //endregion
    //endregion [end]

    //region [start] 批量导出面试成绩
    //下载成绩导入模版
    @RequestMapping("/DowmExcel")
    public void DowmExcel(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            codedFileName = java.net.URLEncoder.encode("面试成绩导入模版", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();

            //[start] 模版表头

            HSSFRow headrow = sheet.createRow(0);//创建一行
            HSSFCell headcel0 = headrow.createCell(0);
            headcel0.setCellValue(new HSSFRichTextString("面试编号"));
            HSSFCell headcel1 = headrow.createCell(1);
            headcel1.setCellValue(new HSSFRichTextString("姓名"));
            HSSFCell headcel2 = headrow.createCell(2);
            headcel2.setCellValue(new HSSFRichTextString("性别"));
            HSSFCell headcel3 = headrow.createCell(3);
            headcel3.setCellValue(new HSSFRichTextString("证件号码"));
            HSSFCell headcel4 = headrow.createCell(4);
            headcel4.setCellValue(new HSSFRichTextString("应聘职位"));
            HSSFCell headcel5 = headrow.createCell(5);
            headcel5.setCellValue(new HSSFRichTextString("面试成绩"));
            HSSFCell headcel6 = headrow.createCell(6);
            headcel6.setCellValue(new HSSFRichTextString("面试评价"));
            HSSFCell headcel7 = headrow.createCell(7);
            headcel7.setCellValue(new HSSFRichTextString("考官编号"));
            HSSFCell headcel8 = headrow.createCell(8);
            headcel8.setCellValue(new HSSFRichTextString("考官姓名"));

            //[end]

            String fid = request.getParameter("fid").trim();
            ProjectInfo project = projectService.getProjectInfo(fid);

            List<Object[]> objs = msService.getMsUser(fid, project.getRecruittype());
            int i = 1;
            for (Object[] obj : objs) {
                HSSFRow row = sheet.createRow(i);//创建一行
                for (int j = 0; j < 9; j++) {
                    HSSFCell cell = row.createCell(j);//创建一列
                    //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(new HSSFRichTextString(obj[j] == null ? "" : obj[j].toString()));
                }
                i++;
            }
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    //下载成绩导入模版
    @RequestMapping("/DowmExcelNoDetial")
    public void DowmExcelNoDetial(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            codedFileName = java.net.URLEncoder.encode("面试成绩导入模版", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();

            //[start] 模版表头

            HSSFRow headrow = sheet.createRow(0);//创建一行
            HSSFCell headcel1 = headrow.createCell(0);
            headcel1.setCellValue(new HSSFRichTextString("姓名"));
            HSSFCell headcel2 = headrow.createCell(1);
            headcel2.setCellValue(new HSSFRichTextString("性别"));
            HSSFCell headcel3 = headrow.createCell(2);
            headcel3.setCellValue(new HSSFRichTextString("身份证号"));
            HSSFCell headcel4 = headrow.createCell(3);
            headcel4.setCellValue(new HSSFRichTextString("应聘职位"));
            HSSFCell headcel5 = headrow.createCell(4);
            headcel5.setCellValue(new HSSFRichTextString("面试成绩"));
            HSSFCell headcel6 = headrow.createCell(5);
            headcel6.setCellValue(new HSSFRichTextString("面试结果"));
            HSSFCell headcel7 = headrow.createCell(6);
            headcel7.setCellValue(new HSSFRichTextString("评分规则"));
            //[end]

            String fid = request.getParameter("fid").trim();
            ProjectInfo project = projectService.getProjectInfo(fid);

            List<Object[]> objs = msService.getMsUserNoExaminer(fid, project.getRecruittype());
            int i = 1;
            for (Object[] obj : objs) {
                HSSFRow row = sheet.createRow(i);//创建一行
                for (int j = 0; j < 5; j++) {
                    HSSFCell cell = row.createCell(j);//创建一列
                    //cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(new HSSFRichTextString(obj[j + 1] == null ? "" : obj[j + 1].toString()));
                }
                i++;
            }
            DVConstraint constraint;
            CellRangeAddressList reslutregions = new CellRangeAddressList(1, 65535, 5, 5); //excel下拉菜单作用域，例子中是第12列(从0开始)
            String[] resultlist = new String[]{"已通过", "待定", "未通过", "未参加"};
            constraint = DVConstraint.createExplicitListConstraint(resultlist); //将list中的内容写入到excel中
            HSSFDataValidation reslut_validation = new HSSFDataValidation(reslutregions, constraint);
            sheet.addValidationData(reslut_validation); //对sheet生效

            CellRangeAddressList regions = new CellRangeAddressList(1, 65535, 6, 6); //excel下拉菜单作用域，例子中是第12列(从0开始)
            String[] ruleslist = new String[]{"三通过", "两过一不过", "一过两不过", "三不通过"};
            constraint = DVConstraint.createExplicitListConstraint(ruleslist); //将list中的内容写入到excel中
            HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
            sheet.addValidationData(data_validation); //对sheet生效
            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }


    //成绩导入页面
    @RequestMapping("/import")
    public String importscore(HttpServletRequest request, Model model) {
        model.addAttribute("pid", request.getParameter("pid").trim());
        model.addAttribute("fid", request.getParameter("fid").trim());
        model.addAttribute("deptcode", request.getParameter("deptcode").trim());
        return "/Do/Ms/import";
    }

    //成绩导入页面无详情
    @RequestMapping("/importnodetial")
    public String importscorenodetial(HttpServletRequest request, Model model) {
        model.addAttribute("pid", request.getParameter("pid").trim());
        model.addAttribute("fid", request.getParameter("fid").trim());
        model.addAttribute("deptcode", request.getParameter("deptcode").trim());
        return "/Do/Ms/importnodetial";
    }

    //成绩导入事件无详情
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = {"/ImportNoDetialAction"}, method = RequestMethod.POST)
    public void ImportNoDetialAction(@RequestParam("excel") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        DataTable dataTable = null;
        org.apache.poi.ss.usermodel.Workbook workbook;
        try {
            String pid = request.getParameter("pid").trim();//招聘方案
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            BaseUser usr = utilService.getSessionUser(request);

            //判断操作用户为否为责任部门
            if (usr.getUdept().equals(deptcode)) {
                if (utilService.FlowIsDoing(fid)) {
                    //Workbook rwb = Workbook.getWorkbook(file.getInputStream());

                    try {
                        dataTable = ExcelHelper.ReadExcelToDataTable(file);
                    } catch (Exception e) {
                        utilService.printJsonResult(false, "只能上传后缀为：xls和xlsx的Excel文件", "no", response);
                    }

                    if (dataTable != null && dataTable.Rows.size() > 0) {
                        Integer cardNoIndex = null;
                        Integer sorceIndex = null;
                        Integer resultIndex = null;
                        Integer rulesIndex = null;
                        for (int i = 0; i < dataTable.Columns.size(); i++) {
                            String columnName = dataTable.Columns.get(i).ColumnName;
                            if (columnName.indexOf("身份证") >= 0) {
                                cardNoIndex = i;
                                continue;
                            }
                            if (columnName.indexOf("成绩") >= 0) {
                                sorceIndex = i;
                                continue;
                            }
                            if (columnName.indexOf("结果") >= 0) {
                                resultIndex = i;
                                continue;
                            }
                            if (columnName.equalsIgnoreCase("评分规则")) {
                                rulesIndex = i;
                                continue;
                            }

                        }
                        if((cardNoIndex!=null)&&(sorceIndex!=null)&&(resultIndex!=null)&&(rulesIndex!=null)){
                            List<DoMSUser> editlist = new ArrayList<DoMSUser>();
                            List<HRZZUser> editZZlist = new ArrayList<HRZZUser>();
                            for (DataRow row : dataTable.Rows) {
                                String cardNo = "";
                                if (cardNoIndex != null) {
                                    cardNo = row.getValue(cardNoIndex).toString();
                                }
                                String sorce = "";
                                if (sorceIndex != null) {
                                    sorce = row.getValue(sorceIndex).toString();
                                }
                                String msresult = "";
                                if (resultIndex != null) {
                                    msresult = row.getValue(resultIndex).toString();
                                }
                                String rulesresult = "";
                                if (rulesIndex != null) {
                                    rulesresult = row.getValue(rulesIndex).toString();
                                }

                                if (cardNo != null && !cardNo.equalsIgnoreCase("")) {
                                    if (!pid.startsWith("C_")) {
                                        List<DUserResume> userResumeList = doResumeService.getDResumeByCardNo(cardNo, pid);
                                        if (userResumeList.size() == 0) {
                                            row.setValue(dataTable.Columns.size() - 1, "身份证不存在!");
                                            continue;
                                        }
                                        if (userResumeList.size() == 1) {
                                            String userId = userResumeList.get(0).getCardno();
                                            DoMSUser msUser = msService.getMsUserByCardNo(fid, userId);
                                            if (msUser != null) {
                                                msUser.setPoint(sorce);
                                                msUser.setResult(msresult);
                                                msUser.setPointuser(usr.getUcode());
                                                msUser.setPointdate(new Date());
                                                msUser.setScoringrules(rulesresult);
                                                try {
                                                    utilService.editObject(msUser);
                                                    row.setValue(dataTable.Columns.size() - 1, "已导入");
                                                } catch (Exception e) {
                                                    row.setValue(dataTable.Columns.size() - 1, "导入失败");
                                                }
                                                //editlist.add(msUser);
                                            }
                                        } else {
                                            row.setValue(dataTable.Columns.size() - 1, "存在多条数据");
                                        }
                                    } else {
                                        List<HRZZUser> hrzzUserList = recommendService.getUserList(pid, cardNo, deptcode);

                                        if (hrzzUserList == null || hrzzUserList.size() == 0) {
                                            row.setValue(dataTable.Columns.size() - 1, "身份证不存在!");
                                            continue;
                                        }

                                        if (hrzzUserList.size() > 1) {
                                            row.setValue(dataTable.Columns.size() - 1, "存在多条数据!");
                                            continue;
                                        }
                                        if (hrzzUserList.size() == 1) {
                                            HRZZUser hrzzUser = hrzzUserList.get(0);
                                            if (hrzzUser != null) {
                                                String userId = hrzzUser.getId();
                                                DoMSUser msUser = msService.getMsUser(fid, userId);
                                                if (msUser != null) {
                                                    msUser.setPoint(sorce);
                                                    msUser.setResult(msresult);
                                                    msUser.setPointuser(usr.getUcode());
                                                    msUser.setPointdate(new Date());
                                                    msUser.setScoringrules(rulesresult);
                                                    hrzzUser.setMsstate(msUser.getResult());
                                                    hrzzUser.setMsresult(msUser.getPoint());
                                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                                    hrzzUser.setMsdate(simpleDateFormat.parse(msUser.getStarttime()));
                                                    try {
                                                        utilService.editObject(msUser);
                                                        utilService.editObject(hrzzUser);
                                                        row.setValue(dataTable.Columns.size() - 1, "已导入");
                                                    } catch (Exception e) {
                                                        row.setValue(dataTable.Columns.size() - 1, "导入失败");
                                                    }
                                                }
                                            }
                                        }

                                    }

                                }
                            }
                            //变更为逐条保存不再使用批量保存
                        /*if(editlist!=null&&editlist.size()>0) {
                            utilService.editList(editlist);
                        }
                        if(editZZlist!=null&&editZZlist.size()>0){
                            utilService.editList(editZZlist);
                        }*/

                            org.apache.poi.ss.usermodel.Workbook reusultbook = ExcelHelper.DataTableToExcel(dataTable, "面试成绩导入结果");
                            try {
                                String fileName = file.getOriginalFilename();
                                //response.setHeader("content-disposition", "attachment;filename=" + fileName.substring(0,fileName.lastIndexOf(".")) + "导入结果.xls");
                                String rfilename = fileName.substring(0, fileName.lastIndexOf(".")) + "导入结果.xls";
                                String uploadPath = request.getServletContext().getRealPath("\\resources\\upload");
                                String rfilepath = uploadPath + "\\excelresult";
                                File rdir = new File(rfilepath);

                                if (rdir.exists()) {
                                    String[] filelist = rdir.list();
                                    for (int i = 0; i < filelist.length; i++) {
                                        File readfile = new File(rfilepath + "\\" + filelist[i]);
                                        readfile.delete();
                                    }
                                } else {
                                    boolean bmkdir = rdir.mkdir();
                                    if (!bmkdir) {
                                        rdir.mkdirs();
                                    }

                                }
                                File rfile = new File(rfilepath + "\\" + rfilename);
                                if (rfile.createNewFile()) {
                                    FileOutputStream fileOutputStream = new FileOutputStream(rfile);
                                    reusultbook.write(fileOutputStream);
                                    utilService.printJsonResult(true, "操作成功！", request.getContextPath() + "/resources/upload/excelresult/" + rfilename, response);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                utilService.printJsonResult(false, "操作失败！", "no", response);
                            }
                        }else{
                            utilService.printJsonResult(false, "该文件不符合要求！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "读取Excel文件错误,未读取到导入数据！", "no", response);
                    }


                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }

                    /*if (addlist.size() > 0) {
                        utilService.addList(dellist, addlist);

                        List<DoMSUser> editlist = new ArrayList<DoMSUser>();
                        //计算总成绩
                        for (DoMSUser msu : msus) {
                            List<DoMSResult> results = msService.getMsResults(msu.getId());
                            //所有考官评分完成，计算总成绩
                            if (msu.getExaminercount() == results.size()) {
                                StringBuffer pointuser = new StringBuffer(",");
                                List<Integer> numerator = new ArrayList<Integer>();   //分子
                                List<Integer> denominator = new ArrayList<Integer>(); //分母
                                int wtgcount = 0;//评分结果选择未通过的数量
                                for (DoMSResult _result : results) {
                                    if (_result.getResult() == 3) {
                                        wtgcount++;
                                    }
                                    if (_result.getUweight().contains("/")) {
                                        numerator.add(_result.getPoint() * Integer.parseInt(_result.getUweight().split("/")[0].trim()));
                                        denominator.add(Integer.parseInt(_result.getUweight().split("/")[1].trim()));
                                    }
                                    if (_result.getUweight().contains("%")) {
                                        numerator.add(_result.getPoint() * Integer.parseInt(_result.getUweight().replace("%", "").trim()));
                                        denominator.add(100);
                                    }

                                    pointuser.append(_result.getCode() + ",");
                                }


                                double rpoint = MathTools.fracAdd1(numerator, denominator);
                                if (rpoint >= 60 && (wtgcount / (double) msu.getExaminercount() <= 1 / (double) 3)) {
                                    msu.setResult("已通过");
                                } else {
                                    msu.setResult("未通过");
                                }
                                msu.setPointuser(pointuser.toString());
                                msu.setPoint(String.valueOf(rpoint));
                                msu.setPointdate(new Date());
                                editlist.add(msu);
                            }
                        }

                        utilService.editList(editlist);
                            utilService.printJsonResult(true, "操作成功", "no", response);
        } else{
            utilService.printJsonResult(false, "无符合条件的信息！", "no", response);
        }
                        */


        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }

    }


    /**
     * @deprecated 修改为直接根据身份中号导入面试成绩和结果, 并支持xlsx
     */
    @Deprecated
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = {"/ImportAction"}, method = RequestMethod.POST)
    public void ImportAction(@RequestParam("excel") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {

        try {
            String exname = StringTools.getFileExtension(file.getOriginalFilename());//扩展名（.xxx）

            if (exname.equals(".xls")) {
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码

                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        Workbook rwb = Workbook.getWorkbook(file.getInputStream());
                        Sheet rs = rwb.getSheet(0);//得到第一个工作表中的数据
                        int rows = rs.getRows();//得到所有的行
                        List addlist = new ArrayList();
                        List dellist = new ArrayList();
                        List<DoMSUser> msus = new ArrayList<DoMSUser>();
                        for (int i = 1; i < rows; i++) {
                            if (rs.getCell(0, i).getContents().length() != 0) {
                                //DoMS_User的ID
                                String id = rs.getCell(0, i).getContents().trim();
                                DoMSUser msuser = msService.getMsUser(id);
                                if (msuser == null) {
                                    utilService.printJsonResult(false, "第" + (i + 1) + "行数据中面试编号错误！", "no", response);
                                    return;
                                }

                                if (!msuser.getFid().equals(fid)) {
                                    utilService.printJsonResult(false, "第" + (i + 1) + "行数据中面试编号错误！", "no", response);
                                    return;
                                }

                                //应聘者的成绩
                                int point = 0;
                                try {
                                    point = Integer.parseInt(rs.getCell(5, i).getContents().trim());
                                } catch (Exception e) {
                                    utilService.printJsonResult(false, "第" + (i + 1) + "行数据中成绩数据格式错误！", "no", response);
                                    return;
                                }

                                //面试结果总表信息
                                DoMSResult result = new DoMSResult();
                                result.setId(UUID.randomUUID().toString());
                                result.setAddtime(new Date());
                                result.setMsuid(id);
                                result.setRemark(rs.getCell(6, i).getContents().trim());//应聘者的评价信息
                                result.setPoint(point);
                                if (point >= 90) {
                                    result.setResult(0);
                                }
                                if (point >= 80 && point <= 89) {
                                    result.setResult(1);
                                }
                                if (point >= 60 && point <= 79) {
                                    result.setResult(2);
                                }
                                if (point < 60) {
                                    result.setResult(3);
                                }

                                //应聘者的考官编号
                                String code = rs.getCell(7, i).getContents().trim();

                                DoMSExaminer examiner = msService.getExaminer(msuser.getGid(), code);
                                if (examiner == null) {
                                    utilService.printJsonResult(false, "第" + (i + 1) + "行数据中考官编号错误！", "no", response);
                                    return;
                                }

                                result.setCode(examiner.getCode());
                                result.setUname(examiner.getUname());
                                result.setUweight(examiner.getUweight());
                                result.setRole(examiner.getRole());
                                addlist.add(result);

                                if (!ObjInList(msus, msuser)) {
                                    msus.add(msuser);
                                }
                                //删除旧评分
                                DoMSResult dResult = msService.getMsResult(id, examiner.getCode());
                                if (dResult != null) {
                                    dellist.add(dResult);
                                }
                                List<DoMSResultDetail> rds = null;
                                try {
                                    rds = msService.getMSResultDetail(dResult.getId());
                                } catch (Exception e) {

                                }
                                if (rds != null) {
                                    dellist.addAll(rds);
                                }
                            } else {
                                break;
                            }
                        }

                        if (addlist.size() > 0) {
                            utilService.addList(dellist, addlist);

                            List<DoMSUser> editlist = new ArrayList<DoMSUser>();
                            //计算总成绩
                            for (DoMSUser msu : msus) {
                                List<DoMSResult> results = msService.getMsResults(msu.getId());
                                //所有考官评分完成，计算总成绩
                                if (msu.getExaminercount() == results.size()) {
                                    StringBuffer pointuser = new StringBuffer(",");
                                    List<Integer> numerator = new ArrayList<Integer>();   //分子
                                    List<Integer> denominator = new ArrayList<Integer>(); //分母
                                    int wtgcount = 0;//评分结果选择未通过的数量
                                    for (DoMSResult _result : results) {
                                        if (_result.getResult() == 3) {
                                            wtgcount++;
                                        }
                                        if (_result.getUweight().contains("/")) {
                                            numerator.add(_result.getPoint() * Integer.parseInt(_result.getUweight().split("/")[0].trim()));
                                            denominator.add(Integer.parseInt(_result.getUweight().split("/")[1].trim()));
                                        }
                                        if (_result.getUweight().contains("%")) {
                                            numerator.add(_result.getPoint() * Integer.parseInt(_result.getUweight().replace("%", "").trim()));
                                            denominator.add(100);
                                        }

                                        pointuser.append(_result.getCode() + ",");
                                    }


                                    double rpoint = MathTools.fracAdd1(numerator, denominator);
                                    if (rpoint >= 60 && (wtgcount / (double) msu.getExaminercount() <= 1 / (double) 3)) {
                                        msu.setResult("已通过");
                                    } else {
                                        msu.setResult("未通过");
                                    }
                                    msu.setPointuser(pointuser.toString());
                                    msu.setPoint(String.valueOf(rpoint));
                                    msu.setPointdate(new Date());
                                    editlist.add(msu);
                                }
                            }

                            utilService.editList(editlist);

                            utilService.printJsonResult(true, "操作成功", "no", response);
                        } else {
                            utilService.printJsonResult(false, "无符合条件的信息！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "只能上传后缀为：xls的Excel文件", "no", response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }

    }

    private boolean ObjInList(List<DoMSUser> msus, DoMSUser msu) {
        for (DoMSUser _msu : msus) {
            if (_msu.getId().equals(msu.getId())) {
                return true;
            }
        }
        return false;
    }

//[end]

//region [start] 公共方法

    //region 获得招聘方案列表
    @RequestMapping("/getproject")
    public void getProjectByPlan(HttpServletRequest request, HttpServletResponse response) {
        try {
            int type = Integer.parseInt(request.getParameter("type"));//招聘方式
            List<ProjectInfo> projects = projectService.getProjectInfos(type);
            StringBuilder pros = new StringBuilder();
            for (ProjectInfo project : projects) {
                if (project.getState() != EnumTools.ProjectState.编辑中.ordinal())
                    pros.append("<option value='" + project.getId() + "'>" + project.getPname() + "</option>");
            }
            utilService.printTextResult(pros.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }
//endregion

    //region 获得面试流程列表
    @RequestMapping("/getflow")
    public void getMSFlow(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案
            ProjectInfo project = projectService.getpProjectById(pid);
            int ftype = -1;
            /*if (project.getRecruittype() == EnumTools.RecruitType.内部招聘.ordinal()) {
                ftype = EnumTools.NZFlowState.面试.ordinal();
            } else*/
            if (project.getRecruittype() == EnumTools.RecruitType.社会招聘.ordinal()) {
                ftype = EnumTools.FlowState.面试.ordinal();
            } else if (project.getRecruittype() == EnumTools.RecruitType.高校校园招聘.ordinal()) {
                ftype = EnumTools.GXFlowState.面试.ordinal();
            } else if (project.getRecruittype() == EnumTools.RecruitType.中专校园招聘.ordinal()) {
                ftype = EnumTools.ZZFlowStateNew.面试.ordinal();
            } else {
            }

            List<ProjectInfoFlow> flows = msService.getFlows(pid, ftype);
            StringBuilder pros = new StringBuilder();
            for (ProjectInfoFlow flow : flows) {
                pros.append("<option value='" + flow.getId() + "'>" + flow.getNickname() + " (" + flow.getDeptname() + ")</option>");
            }
            utilService.printTextResult(pros.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("", response);
        }
    }
//endregion

    //region 录入面试成绩
    @RequestMapping("/score")
    public String score(HttpServletRequest request, Model model) {
        try {
            String uid = request.getParameter("uid").trim();//面试者ID（DoMSUser的主键）
            model.addAttribute("uid", uid);
            DoMSUser msuser = msService.getMsUser(uid);
            model.addAttribute("tname", msuser.getEvaluationname());
            ProjectInfo project = msService.getProjectByFid(msuser.getFid());
            model.addAttribute("num", msuser.getNum());
            /*if (project.getRecruittype() == EnumTools.RecruitType.内部招聘.ordinal()) {
                DNZResume resume = nzService.getDResume(msuser.getUserid());
                model.addAttribute("msinfo", "应聘岗位：" + resume.getJname() + "&emsp;&emsp;&emsp;应试人员序号：" + msuser.getNum());
            } else */
            if (project.getRecruittype() == EnumTools.RecruitType.社会招聘.ordinal()) {
                DUserResume resume = szService.getResume(msuser.getUserid());
                model.addAttribute("msinfo", "应聘岗位：" + resume.getJname() + "&emsp;&emsp;&emsp;应试人员序号：" + msuser.getNum());
            } else if (project.getRecruittype() == EnumTools.RecruitType.中专校园招聘.ordinal()) {
                model.addAttribute("msinfo", "应聘岗位：待定&emsp;&emsp;&emsp;应试人员序号：" + msuser.getNum());
            } else if (project.getRecruittype() == EnumTools.RecruitType.高校校园招聘.ordinal()) {
                model.addAttribute("msinfo", "应聘岗位：待定&emsp;&emsp;&emsp;应试人员序号：" + msuser.getNum());
            } else {

            }
            BaseUser cUser = utilService.getSessionUser(request);

            //已经评分
            if (msuser.getPointuser().contains(cUser.getUcode())) {
                DoMSResult result = msService.getMsResult(uid, cUser.getUcode());
                model.addAttribute("remark", result.getRemark() == null ? "" : result.getRemark());
                List<DoMSResultDetail> details = msService.getMSResultDetail(result.getId());
                model.addAttribute("items", details);
                model.addAttribute("type", "");
            } else {//未评分
                List<DoMSEvaluation> items = msService.getMSEvaluations(msuser.getGid());
                model.addAttribute("items", items);
                model.addAttribute("type", "add");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/Do/Ms/score";
    }
//endregion

    //region 录入面试成绩
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/ScoreAction", method = RequestMethod.POST)
    public void ScoreAction(HttpServletRequest request, HttpServletResponse response, DoMSResultForm form) {
        try {
            BaseUser cuser = utilService.getSessionUser(request);
            DoMSUser msuser = msService.getMsUser(form.getMsuid());//参加面试的应聘者

            ProjectInfo project = msService.getProjectByFid(msuser.getFid());
            if (project.getRecruittype() == EnumTools.RecruitType.社会招聘.ordinal()) {
                DUserResume resume = szService.getResume(msuser.getUserid());
                if (!resume.getFid().equals(msuser.getFid())) {
                    utilService.printJsonResult(false, "面试结束，不能执行此操作！", "no", response);
                    return;
                }
            } /*else if (project.getRecruittype() == EnumTools.RecruitType.内部招聘.ordinal()) {
                DNZResume resume = nzService.getDResume(msuser.getUserid());
                if (!resume.getFid().equals(msuser.getFid())) {
                    utilService.printJsonResult(false, "面试结束，不能执行此操作！", "no", response);
                    return;
                }
            } */else if (project.getRecruittype() == EnumTools.RecruitType.中专校园招聘.ordinal()) {
                HRZZUser resume = recommendService.getUser(msuser.getUserid());
                if (!resume.getFid().equals(msuser.getFid())) {
                    utilService.printJsonResult(false, "面试结束，不能执行此操作！", "no", response);
                    return;
                }
            } else if (project.getRecruittype() == EnumTools.RecruitType.高校校园招聘.ordinal()) {
                DUserResume resume = szService.getResume(msuser.getUserid());
                if (!resume.getFid().equals(msuser.getFid())) {
                    utilService.printJsonResult(false, "面试结束，不能执行此操作！", "no", response);
                    return;
                }
            }

            List addlist = new ArrayList();
            String id = UUID.randomUUID().toString();

            //面试结果详细得分信息
            int point = 0;
            for (DoMSResultDetail detail : form.getEva()) {
                detail.setId(UUID.randomUUID().toString());
                detail.setMsrid(id);
                addlist.add(detail);
                point += detail.getPoint();
            }

            //面试结果总表信息
            DoMSResult result = new DoMSResult();
            result.setId(id);
            result.setAddtime(new Date());
            result.setMsuid(form.getMsuid());
            result.setRemark(form.getRemark());
            result.setPoint(point);
            if (point >= 90) {
                result.setResult(0);
            }
            if (point >= 80 && point <= 89) {
                result.setResult(1);
            }
            if (point >= 60 && point <= 79) {
                result.setResult(2);
            }
            if (point < 60) {
                result.setResult(3);
            }

            DoMSExaminer examiner = msService.getExaminer(msuser.getGid(), cuser.getUcode());
            result.setCode(examiner.getCode());
            result.setUname(examiner.getUname());
            result.setUweight(examiner.getUweight());
            result.setRole(examiner.getRole());
            addlist.add(result);

            List<DoMSResult> results = msService.getMsResultNoMe(form.getMsuid(), examiner.getCode());
            boolean flag = false;
            //所有考官评分完成，计算总成绩
            if (msuser.getExaminercount() - results.size() == 1) {
                List<Integer> numerator = new ArrayList<Integer>();   //分子
                List<Integer> denominator = new ArrayList<Integer>(); //分母
                int wtgcount = 0;//评分结果选择未通过的数量
                for (DoMSResult _result : results) {
                    if (_result.getResult() == 3) {
                        wtgcount++;
                    }
                    if (_result.getUweight().contains("/")) {
                        numerator.add(_result.getPoint() * Integer.parseInt(_result.getUweight().split("/")[0].trim()));
                        denominator.add(Integer.parseInt(_result.getUweight().split("/")[1].trim()));
                    } else if (_result.getUweight().contains("%")) {
                        numerator.add(_result.getPoint() * Integer.parseInt(_result.getUweight().replace("%", "").trim()));
                        denominator.add(100);
                    } else {
                        flag = true;
                        break;
                    }
                }

                if (result.getResult() == 3) {
                    wtgcount++;
                }

                if (result.getUweight().contains("/")) {
                    numerator.add(result.getPoint() * Integer.parseInt(result.getUweight().split("/")[0].trim()));
                    denominator.add(Integer.parseInt(result.getUweight().split("/")[1].trim()));
                } else if (result.getUweight().contains("%")) {
                    numerator.add(result.getPoint() * Integer.parseInt(result.getUweight().replace("%", "").trim()));
                    denominator.add(100);
                } else {
                    flag = true;
                }

                double rpoint = MathTools.fracAdd1(numerator, denominator);
                if (!flag) {
                    if (rpoint >= 60 && (wtgcount / (double) msuser.getExaminercount() <= 1 / (double) 3)) {
                        msuser.setResult("已通过");
                    } else {
                        msuser.setResult("未通过");
                    }
                    msuser.setPoint(String.valueOf(rpoint));
                    msuser.setPointdate(new Date());
                } else {
                    utilService.printJsonResult(false, "操作失败！", "no", response);
                    return;
                }

            }

            //已经评分
            if (msuser.getPointuser().contains("," + cuser.getUcode() + ",")) {
                List dellist = new ArrayList();
                //删除面试结果信息
                DoMSResult dResult = msService.getMsResult(form.getMsuid(), examiner.getCode());
                dellist.add(dResult);
                dellist.addAll(msService.getMSResultDetail(dResult.getId()));

                utilService.editList(msuser, dellist, addlist);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            } else {//未评分
                msuser.setPointuser(msuser.getPointuser() + examiner.getCode() + ",");
                utilService.editObject(msuser, addlist);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
//endregion


    @RequestMapping("/viewResult")
    public String viewResult(HttpServletRequest request, Model model) {
        try {
            String uid = request.getParameter("uid").trim();
            String uname = request.getParameter("uname").trim();
            DoMSUser user = msService.getMsUser(uid);
            model.addAttribute("user", user);
            model.addAttribute("uname", uname);
            List<DoMSResult> results = msService.getMsResults(uid);
            model.addAttribute("results", results);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "/Do/Ms/viewscore";
    }

    //endregion [end]

    //更新面试结果
    @RequestMapping(value = "/resultUpdate")
    public void msResultUpdate(HttpServletRequest request, HttpServletResponse response) {
        String pid = request.getParameter("pid");
        String fid = request.getParameter("fid");
        String deptcode = request.getParameter("deptcode");
        String ids = request.getParameter("ids");
        String state = request.getParameter("state");
        if (state == null || state.equalsIgnoreCase("")) {
            state = "未面试";
        }
        BaseUser baseUser = utilService.getSessionUser(request);
        if (baseUser == null) {
            utilService.printJsonResult(false, "登录状态过期,请重新登录！", "no", response);
            return;
        }
        if (baseUser.getUdept().equals(deptcode)) {
            //流程是否结束
            if (utilService.FlowIsDoing(fid)) {

                if (ids != null && ids.length() > 0) {
                    String[] idArray = ids.split(",");
                    try {
                        if (idArray.length > 0) {
                            List<Object> editList = new ArrayList<Object>();

                            List<DoMSUser> doMSUserList = msService.getMsUsers(idArray, fid);
                            for (DoMSUser msUser : doMSUserList) {
                                if (msUser.getFid().equals(fid)) {
                                    msUser.setResult(state);
                                    msUser.setPointdate(new Date());
                                    msUser.setPointuser(baseUser.getUname());
                                    editList.add(msUser);
                                }
                            }

                            if ((pid.indexOf("C_") >= 0)&&((pid.indexOf("E_")>=0))) {
                                for (int i = 0; i < idArray.length; i++) {
                                    HRZZUser hrzzUser = recommendService.getUser(idArray[i]);
                                    hrzzUser.setMsresult(state);
                                    hrzzUser.setMsuid(baseUser.getId());
                                    hrzzUser.setMsuname(baseUser.getUname());
                                    hrzzUser.setMsdate(new Date());
                                    editList.add(hrzzUser);
                                }
                            }
                            utilService.editList(editList);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        utilService.printJsonResult(false, "操作失败！", "no", response);
                    }


                } else {
                    utilService.printJsonResult(false, "请选择应聘者！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
            }
        } else {
            utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
        }

    }

    //region 面试批次相关信息管理

    //region 面试批次管理首页
    @RequestMapping(value = "/msbatch")
    public String msBatch() {
        return "/Do/Ms/msbatch";
    }

    //endregion
    @RequestMapping(value = "/queryMsBatch")
    public void queryMsBatch(HttpServletRequest request, HttpServletResponse response) {
        int perpage = Integer.parseInt(request.getParameter("perpage"));
        int page = Integer.parseInt(request.getParameter("page"));
        String mspch = request.getParameter("mspch");
        String pname = request.getParameter("pname");
        String recruittype = request.getParameter("recruittype");
        String jname = request.getParameter("jname");
        String msaddress = request.getParameter("msaddress");
        String msstarttime = request.getParameter("msstarttime");
        String ucardno = request.getParameter("ucardno");
        String uname = request.getParameter("uname");
        String filename = request.getParameter("filename");
        try {
            Map<String, Object> msBatchs = msService.queryMsBatch(page, perpage, mspch, pname, recruittype, jname, msaddress, msstarttime, ucardno, uname, filename);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) msBatchs.get("pageCount");
            double allcount = (Double) msBatchs.get("count");

            if (pageCount != 0) {
                Object object = msBatchs.get("list");
                int num = 1;
                for (Object[] batch : (List<Object[]>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" + batch[0] + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + batch[0] + "</td>");
                    result.append("<td style='display:none'>" + batch[1] + "</td>");
                    result.append("<td>" + batch[2] + "</td>");
                    if (batch[3].toString().equalsIgnoreCase("3")) {
                        result.append("<td>社招</td>");
                    } else if (batch[3].toString().equalsIgnoreCase("1")) {
                        result.append("<td>校招</td>");
                    } else if (batch[3].toString().equalsIgnoreCase("2")) {
                        result.append("<td>中专</td>");
                    } else if (batch[3].toString().equalsIgnoreCase("4")) {
                        result.append("<td>内部</td>");
                    }

                    result.append("<td>" + batch[4] + "</td>");
                    result.append("<td style='display:none'>" + batch[5] + "</td>");
                    result.append("<td>" + batch[6] + "</td>");
                    result.append("<td>" + batch[7] + "</td>");
                    result.append("<td>" + batch[8] + "</td>");
                    result.append("<td>" + batch[9] + "</td>");
                    result.append("<td><a onClick=userDetial(this) style='color:#2b72dc;'>人员详情</a><a style='color:#2b72dc;' onClick=enclosureDetial(this)>附件详情</a></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='9'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/queryMsBatchJson")
    public LayuiDataTableResultBean queryMsBatchJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int limit = Integer.parseInt(request.getParameter("limit"));
            int page = Integer.parseInt(request.getParameter("page"));
            String mspch = request.getParameter("mspch");
            String pname = request.getParameter("pname");
            String recruittype = request.getParameter("recruittype");
            String jname = request.getParameter("jname");
            String msaddress = request.getParameter("msaddress");
            String msstarttime = request.getParameter("msstarttime");
            String ucardno = request.getParameter("ucardno");
            String uname = request.getParameter("uname");
            String filename = request.getParameter("filename");
            Map<String, Object> map = msService.queryMsBatch(page, limit, mspch, pname, recruittype, jname, msaddress, msstarttime, ucardno, uname, filename);
            List<Object[]> list = (List<Object[]>) map.get("list");
            JSONArray data = new JSONArray();
            for (Object[] im :
                    list) {
                JSONObject item = new JSONObject();
                item.put("mspch", im[0]);
//                item.put("pid", im[1]);
                item.put("pname", im[2]);
//                item.put("recruittype", im[3]);
                item.put("jname", im[4]);
//                item.put("jid", im[5]);
                item.put("address", im[6]);
                item.put("starttime", im[7]);
                item.put("mspcrs", im[8]);
                item.put("msfjgs", im[9]);
                String type = "";
                if ("1".equals(im[3].toString())) {
                    type = "校招";
                } else if ("2".equals(im[3].toString())) {
                    type = "中专";
                } else if ("3".equals(im[3].toString())) {
                    type = "社招";
                } else if ("4".equals(im[3].toString())) {
                    type = "内部";
                } else if ("5".equals(im[3].toString())) {
                    type = "驾驶员";
                }
                item.put("type", type);
                data.add(item);
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }


    //region 批次人员管理首页
    @RequestMapping(value = "/msbatchuser")
    public String msBatchuser() {
        return "/Do/Ms/msbatchuser";
    }

    @RequestMapping(value = "/queryMsBatchUser")
    public void queryMsBatchUser(HttpServletRequest request, HttpServletResponse response) {
        int perpage = Integer.parseInt(request.getParameter("perpage"));
        int page = Integer.parseInt(request.getParameter("page"));
        String mspch = request.getParameter("mspch");
        String pname = request.getParameter("pname");
        String recruittype = request.getParameter("recruittype");
        String jname = request.getParameter("jname");
        String msaddress = request.getParameter("msaddress");
        String msstarttime = request.getParameter("msstarttime");
        String ucardno = request.getParameter("ucardno");
        String uname = request.getParameter("uname");
        String filename = request.getParameter("filename");
        try {
            Map<String, Object> msBatchs = msService.queryMsBatchUser(page, perpage, mspch, pname, recruittype, jname, msaddress, msstarttime, ucardno, uname, filename);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) msBatchs.get("pageCount");
            double allcount = (Double) msBatchs.get("count");

            if (pageCount != 0) {
                Object object = msBatchs.get("list");
                int num = 1;
                for (Object[] batch : (List<Object[]>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" + batch[0] + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + batch[1] + "</td>");
                    result.append("<td>" + batch[2] + "</td>");
                    result.append("<td>" + batch[3] + "</td>");
                    result.append("<td>" + batch[4] + "</td>");
                    result.append("<td>" + batch[5] + "</td>");
                    result.append("<td>" + batch[6] + "</td>");
                    result.append("<td>" + batch[7] + "</td>");
                    result.append("<td>" + batch[8] + "</td>");
                    result.append("<td>" + batch[9] + "</td>");
                    result.append("<td>" + batch[10] + "</td>");
                    result.append("<td>" + batch[11] + "</td>");
                    result.append("</tr>");
                    // result.append("<td><a onClick=userDetial('"+batch[0].toString()+"') style='color:#2b72dc;'>人员详情</a><a style='color:#2b72dc;' onClick=enclosureDetial('"+batch[0].toString()+"')>附件详情</a></td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='9'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }


    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/queryMsBatchUserJson")
    public LayuiDataTableResultBean queryMsBatchUserJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int limit = Integer.parseInt(request.getParameter("limit"));
            int page = Integer.parseInt(request.getParameter("page"));
            String mspch = request.getParameter("mspch");
            String pname = request.getParameter("pname");
            String recruittype = request.getParameter("recruittype");
            String jname = request.getParameter("jname");
            String msaddress = request.getParameter("msaddress");
            String msstarttime = request.getParameter("msstarttime");
            String ucardno = request.getParameter("ucardno");
            String uname = request.getParameter("uname");
            String filename = request.getParameter("filename");
            Map<String, Object> map = msService.queryMsBatchUser(page, limit, mspch, pname, recruittype, jname, msaddress, msstarttime, ucardno, uname, filename);
            List<Object[]> list = (List<Object[]>) map.get("list");
            JSONArray data = new JSONArray();
            for (Object[] im :
                    list) {
                JSONObject item = new JSONObject();
                item.put("0", im[0]);
                item.put("1", im[1]);
                item.put("2", im[2]);
                item.put("3", im[3]);
                item.put("4", im[4]);
                item.put("5", im[5]);
                item.put("6", im[6]);
                item.put("7", im[8]);
                item.put("8", im[7]);
                item.put("9", im[9]);
                item.put("10", im[10]);
                item.put("11", im[11]);
                data.add(item);
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //endregion

    //region 批次附件管理
    @RequestMapping(value = "/msenclosure")
    public String msEnclosure() {
        return "/Do/Ms/msenclosure";
    }
    //endregion


    @RequestMapping(value = "/queryMsBatchFile")
    public void queryMsBatchFile(HttpServletRequest request, HttpServletResponse response) {
        int perpage = Integer.parseInt(request.getParameter("perpage"));
        int page = Integer.parseInt(request.getParameter("page"));
        String mspch = request.getParameter("mspch");
        String pname = request.getParameter("pname");
        String recruittype = request.getParameter("recruittype");
        String jname = request.getParameter("jname");
        String msaddress = request.getParameter("msaddress");
        String msstarttime = request.getParameter("msstarttime");
        String filename = request.getParameter("filename");
        try {
            Map<String, Object> msBatchs = msService.queryMsBatchFile(page, perpage, mspch, pname, recruittype, jname, msaddress, msstarttime, filename);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) msBatchs.get("pageCount");
            double allcount = (Double) msBatchs.get("count");

            if (pageCount != 0) {
                Object object = msBatchs.get("list");
                int num = 1;
                for (Object[] batch : (List<Object[]>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id='cb_" + batch[0] + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + batch[1] + "</td>");
                    result.append("<td>" + batch[2] + "</td>");
                    result.append("<td>" + batch[3] + "</td>");
                    result.append("<td>" + batch[4] + "</td>");
                    result.append("<td>" + batch[5] + "</td>");
                    result.append("<td style='display:none'>" + batch[6] + "</td>");
                    result.append("<td>" + batch[7] + "</td>");
                    result.append("<td style='display:none'>" + batch[8] + "</td>");
                    result.append("<td>" + batch[9] + "</td>");
                    result.append("<td><a onClick=showDetial('" + batch[0].toString() + "') style='color:#2b72dc;'>详情</a><a style='color:#2b72dc;margin-left:5px;' onClick=downfile('" + batch[0].toString() + "')>下载</a></td>");
                    result.append("</tr>");
                    num++;
                }
            } else {
                result.append("<tr><td colspan='13'>未查询到相关数据!</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='13'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/queryMsBatchFileJson")
    public LayuiDataTableResultBean queryMsBatchFileJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int limit = Integer.parseInt(request.getParameter("limit"));
            int page = Integer.parseInt(request.getParameter("page"));
            String mspch = request.getParameter("mspch");
            String pname = request.getParameter("pname");
            String recruittype = request.getParameter("recruittype");
            String jname = request.getParameter("jname");
            String msaddress = request.getParameter("msaddress");
            String msstarttime = request.getParameter("msstarttime");
            String filename = request.getParameter("filename");
            Map<String, Object> map = msService.queryMsBatchFile(page, limit, mspch, pname, recruittype, jname, msaddress, msstarttime, filename);
            List<Object[]> list = (List<Object[]>) map.get("list");
            JSONArray data = new JSONArray();
            for (Object[] im :
                    list) {
                JSONObject item = new JSONObject();
                item.put("0", im[0]);
                item.put("1", im[1]);
                item.put("2", im[2]);
                item.put("3", im[3]);
                item.put("4", im[4]);
                item.put("5", im[5]);
                item.put("6", im[6]);
                item.put("7", im[7]);
                item.put("8", im[8]);
                item.put("9", im[9]);
                data.add(item);
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double) map.get("count")).intValue());
            result.setData(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //region 导入面试批次附件
    @RequestMapping(value = "/msenclosureimport")
    public String msenclosureimport(HttpServletRequest request, HttpServletResponse response, Model model) {
        String mspch = request.getParameter("mspch");
        String pid = request.getParameter("pid");
        String pname = request.getParameter("pname");
        String jid = request.getParameter("jid");
        String jname = request.getParameter("jname");
        model.addAttribute("mspch", mspch);
        model.addAttribute("pid", pid);
        model.addAttribute("pname", pname);
        model.addAttribute("jid", jid);
        model.addAttribute("jname", jname);
        return "/Do/Ms/msenclosureimport";

    }

    @ResponseBody
    @RequestMapping(value = "/MsEnclosureUpload", method = RequestMethod.POST)
    public ResultBean MsEnclosureUpload(@RequestParam("upfile") MultipartFile file, HttpServletRequest request) {
        ResultBean resultBean = new ResultBean();
        try {

            String mspch = request.getParameter("mspch");
            String pid = request.getParameter("pid");
            String pname = request.getParameter("pname");
            String jid = request.getParameter("jid");
            String jname = request.getParameter("jname");
            BaseUser usr = utilService.getSessionUser(request);
            DoMsEnclosure doMsEnclosure = new DoMsEnclosure();
            doMsEnclosure.setId(UUID.randomUUID().toString());
            doMsEnclosure.setMspch(mspch);
            doMsEnclosure.setPid(pid);
            doMsEnclosure.setPname(pname);
            doMsEnclosure.setUploaduser(usr.getUname());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            doMsEnclosure.setUploadtime(simpleDateFormat.format(new Date()));
            doMsEnclosure.setFilename(file.getOriginalFilename());
            doMsEnclosure.setFilesize(file.getSize() / 1024 + "K");
            doMsEnclosure.setFilecontent(file.getBytes());
            doMsEnclosure.setJid(jid);
            doMsEnclosure.setJname(jname);
            utilService.addObject(doMsEnclosure);
            //InputStream inputStream=multipartFile.getInputStream();
            //Blob file = Hibernate.getLobCreator().createBlob(inputStream, inputStream.available());
            resultBean.setState(true);
            resultBean.setMessage("操作成功!");
            resultBean.setUrl("no");
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("操作失败!");
            resultBean.setUrl("no");
        }

        return resultBean;
    }

    @ResponseBody
    @RequestMapping(value = "/MsEnclosureDown")
    public ResultBean MsEnclosureDown(HttpServletRequest request) {
        ResultBean resultBean = new ResultBean();
        try {

            String fileid = request.getParameter("id");
            if (fileid != null && fileid.trim().length() > 0) {
                DoMsEnclosure doMsEnclosure = msService.getMsBatchFile(fileid);
                String path = "/upload/" + doMsEnclosure.getMspch() + "/";

                File dirs = new File(request.getSession().getServletContext().getRealPath(path));
                if (!dirs.exists()) {
                    dirs.mkdirs();

                }
                String filepath = path + doMsEnclosure.getFilename();
                File file = new File(request.getSession().getServletContext().getRealPath(filepath));
                if (!file.exists()) {
                    file.setReadable(true);
                    file.setWritable(true);
                    FileOutputStream outputStream = new FileOutputStream(file);
                    outputStream.write(doMsEnclosure.getFilecontent());
                    resultBean.setState(true);
                    resultBean.setMessage("操作成功!");
                    resultBean.setUrl(filepath);
                } else {
                    resultBean.setState(true);
                    resultBean.setMessage("操作成功!");
                    resultBean.setUrl(filepath);
                }

            } else {
                resultBean.setState(true);
                resultBean.setMessage("操作成功!");
                resultBean.setUrl("no");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultBean.setState(false);
            resultBean.setMessage("操作失败!");
            resultBean.setUrl("no");
        }

        return resultBean;
    }

    //endregion
    //endregion

    //region 20190304 保存单个面试结果
    @ResponseBody
    @RequestMapping(value = "/SingleResultAction")
    public void SingleResultAction(HttpServletRequest request, HttpServletResponse response) {
        String pid = request.getParameter("pid");
        String fid = request.getParameter("fid");
        String deptcode = request.getParameter("deptcode");
        String ids = request.getParameter("ids");
        String qaremark = request.getParameter("qaremark");
        String qapoint = request.getParameter("qapoint");
        String qaresult = request.getParameter("qaresult");

        ResultBean resultBean = new ResultBean();
        BaseUser baseUser = utilService.getSessionUser(request);
        if (baseUser == null) {
            utilService.printJsonResult(false, "登录状态过期,请重新登录！", "no", response);
        }
        if (StringTools.trimNotEmpty(ids)) {
            String[] userids = null;
            try {
                if (ids.lastIndexOf(",") > 0) {
                    ids = ids.substring(0, ids.lastIndexOf(","));
                    userids = ids.split(",");
                }
                if (userids != null && userids.length > 0) {
                    for (String userid : userids) {
                        DoSSUser ssUser = msService.getSsUser(fid, userid);
                        int count = 1 + msService.getSsCount(fid);
                        if (ssUser == null) {
                            ssUser = new DoSSUser();
                            String msid = UUID.randomUUID().toString();
                            ssUser.setId(msid);
                            ssUser.setPoint(qapoint);
                            ssUser.setPointuser(baseUser.getUname());
                            ssUser.setPointdate(new Date(System.currentTimeMillis()));
                            ssUser.setResult(qaresult);
                            ssUser.setFid(fid);
                            ssUser.setOp8("未公布");
                            ssUser.setUserid(userid);
                            ssUser.setNotice(EnumTools.NoticeState.未发通知.ordinal());
                            if (StringTools.trimNotEmpty(qaremark)) {
                                ssUser.setBz(qaremark);
                            }
                            utilService.addObject(ssUser);
                        } else {
                            ssUser.setPoint(qapoint);
                            ssUser.setPointuser(baseUser.getUname());
                            ssUser.setPointdate(new Date(System.currentTimeMillis()));
                            ssUser.setResult(qaresult);
                            ssUser.setOp8("未公布");
                            utilService.editObject(ssUser);
                        }
                    }
                    utilService.printJsonResult(true, "操作成功！", "no", response);
                }
            } catch (Exception e) {
                e.printStackTrace();

                utilService.printJsonResult(false, "操作失败！", "no", response);
            }


        } else {
            utilService.printJsonResult(false, "至少选择一条信息！", "no", response);
        }

    }
    //endregion


}
